Ext.define('Seq.tree.NaviTree', {
    extend: 'Ext.tree.Panel',
    xtype: 'xnavitree',

    ui: 'light',
    cls: 'box-border-panel',

    header: {
        height: 36,
        padding: 0,
        cls: 'navitree-header',
        items: [{
            xtype: 'xtreefilter',
            cls: 'navitree-search'
        }]
    },
    scrollable: true,
    rootVisible: false,
    width: 280,
    minWidth: 240,
    maxWidth: 400,
    split: {
        size: 5
    },
    reference: 'navitree',

    listeners: {
        select: 'onNaviTreeSelect',

        globalExpand: 'onGlobalExpand',

        load(store, records, successful, operation, node, eOpts) {
            let me = this, selected = me.getSelection();
            if (successful && records.length > 0 && me.isVisible()) {
                let global = Ext.getApplication().getMainView().getViewModel().getData().global_tree_record;
                if (node.parentNode == null) {
                    if (global) {
                        // 根节点是自动展开的，需要手工触发一次
                        me.fireEvent('globalExpand', me, global);
                    } else if (0 == selected.length) {
                        me.getSelectionModel().select(0);
                    }
                }
            }
        },

        viewready(me, opts) {
            let selected = me.getSelection(), store = me.getStore();
            if (selected.length == 0) {
                let root = store && store.getRootNode() || me.getRootNode();
                me.rootVisible && 'root' != root.data.id && selected.push(root);
                (selected.length == 0) && root.firstChild && selected.push(root.firstChild);
                (selected.length > 0) && me.getSelectionModel().select(selected);
            }
        },

        refreshnode(tree, selection, item) {
            let child = selection.findChildBy(function (node) {
                return node.data.id == id;
            });
            if (!child) {
                selection.getTreeStore().load({
                    node: selection
                });
            } else {
                child.set('text', item.data.name, {
                    commit: true
                });
            }
        },

        removenode(tree, selection, items) {
            Ext.Array.forEach(items, function (item) {
                let child = selection.findChildBy(function (node) {
                    return node.data.id == id;
                });
                child && child.remove();
            });
        }
    }

});